package com.ityuan.springcloud.zuul.filter;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

@Component
public class LoginZuulFilter extends ZuulFilter {
	private static Logger log = LoggerFactory.getLogger(LoginZuulFilter.class);

	@Override
	public String filterType() {
		return "pre";
	}

	/**
	 * filter执行顺序，通过数字指定
	 * @return
	 */
	@Override
	public int filterOrder() {
		return 0;
	}

	/**
	 * filter是否需要执行 true执行 false 不执行
	 * @return
	 */
	@Override
	public boolean shouldFilter() {
		 RequestContext requestContext = RequestContext.getCurrentContext();
	        HttpServletRequest request = requestContext.getRequest();
//		if (request.getRequestURI().contains("get")) {
//			return true;
//		}
		return false;
	}

	/**
	 * filter具体逻辑
	 * @return
	 */
	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
		}
		log.info(String.format("自定义zuul过滤器拦截请求：%s >>> %s", request.getMethod(), request.getRequestURL().toString()));

//		// 这里就简单的判断一下是否有token参数，只作为测试
//		Object accessToken = request.getParameter("token");
//		if (accessToken == null) {
//			log.warn("token is empty");
//			ctx.setSendZuulResponse(false);
//			ctx.setResponseStatusCode(401);
//			try {
//				HttpServletResponse res = ctx.getResponse();
//				res.getWriter().write("token is empty");
//			} catch (Exception e) {
//			}
//
//			return null;
//		}
		log.info("自定义zuul过滤器处理完成 ok！");
		return null;
	}
}
